﻿using PetaPoco.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace PetaPoco
{
    /// <summary>
    /// SQLServer 数据库实现类
    /// </summary>
    internal class SqlServerBatchProvider : BatchProvider
    {
        private static readonly Func<IDatabase, SqlConnection> SqlConnectionResolver = db => (SqlConnection)db.Connection;
        private static readonly Func<IDatabase, SqlTransaction> SqlTransactionResolver = db => (SqlTransaction)db.Transaction;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">IDatabase 实例</param>
        public SqlServerBatchProvider(IDatabase db) : base(db)
        {
            SupportBulk = true;
        }

        /// <summary>
        /// 获得/设置 条目阈值 默认 512
        /// </summary>
        public int Limit { get; set; } = 512;

        /// <summary>
        /// 批次插入业务实体类，根据Limit自动判断是Bulk插入还是Batch插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pocos"></param>
        protected override void InsertBulk<T>(IEnumerable<T> pocos)
        {
            var pd = PocoData.ForType(typeof(T), Database.DefaultMapper);

            if (pocos.Count() >= Limit)
            {
                InsertBulkImpl(pd, pocos);
            }
            else
            {
                InsertBatch(pd, pocos);
            }
        }

        /// <summary>
        /// 批次插入业务实体类，根据Limit自动判断是Bulk插入还是Batch插入
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="pocos"></param>
        protected override void InsertBulk(string tableName, IEnumerable<object> pocos)
        {
            var pd = PocoData.ForType(pocos.First().GetType(), Database.DefaultMapper);
            pd.TableInfo.TableName = tableName;

            if (pocos.Count() >= Limit)
            {
                InsertBulkImpl(pd, pocos);
            }
            else
            {
                InsertBatch(pd, pocos);
            }
        }

        private void InsertBulkImpl<T>(PocoData pd, IEnumerable<T> pocos)
        {
            try
            {
                Database.OpenSharedConnection();
                using (var bulkCopy = new SqlBulkCopy(SqlConnectionResolver(Database), SqlBulkCopyOptions.Default, SqlTransactionResolver(Database)))
                {
                    var table = new DataTable();
                    var cols = pd.Columns.Where(x => !x.Value.ResultColumn
                        && !(pd.TableInfo.AutoIncrement && x.Value.ColumnName.Equals(pd.TableInfo.PrimaryKey, StringComparison.OrdinalIgnoreCase))).ToList();

                    foreach (var col in cols)
                    {
                        bulkCopy.ColumnMappings.Add(col.Value.PropertyInfo.Name, col.Value.ColumnName);
                        table.Columns.Add(col.Value.PropertyInfo.Name, Nullable.GetUnderlyingType(col.Value.PropertyInfo.PropertyType) ?? col.Value.PropertyInfo.PropertyType);
                    }

                    foreach (var item in pocos)
                    {
                        var values = new object[cols.Count];
                        for (var i = 0; i < values.Length; i++)
                        {
                            var value = cols[i].Value.GetValue(item);
                            if (Database.DefaultMapper != null)
                            {
                                var fn = Database.DefaultMapper.GetToDbConverter(cols[i].Value.PropertyInfo);
                                if (fn != null) value = fn(value);
                            }
                            values[i] = value;
                        }
                        table.Rows.Add(values);
                    }

                    bulkCopy.DestinationTableName = pd.TableInfo.TableName;
                    bulkCopy.WriteToServer(table);
                }
            }
            finally
            {
                Database.CloseSharedConnection();
            }
        }
    }
}
